package sisicotren.ui.windows;

import javax.swing.JPanel;

import sisicotren.ui.simulator.ScreenElement;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;

public class SimulatorActionPanel extends JPanel {
	
	private static final long serialVersionUID = 1L;
	public SimulatorActionPanel() {
		this.channels = new LinkedList<ScreenElement>();
		this.queues = new LinkedList<ScreenElement>();
		this.getDobleBuffer();
	}
	
	public SimulatorActionPanel(List<ScreenElement> channels, List<ScreenElement> queues) {
		this.channels = channels;
		this.queues = queues;
		this.getDobleBuffer();
	}
	
	private Image getDobleBuffer() {
		if(this.doubleBuffer == null) {
			Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
			this.doubleBuffer = this.createImage((int)scr.getWidth(), (int)scr.getHeight());
		}
		return this.doubleBuffer;
	}
		
	public void clear() {
		this.drawBg = true;
		this.repaint();
	}
	
	public void paintComponent(Graphics g) {
		Graphics _g = this.getDobleBuffer().getGraphics();
		Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
		
		if(drawBg) {
			Color old = _g.getColor();
			_g.setColor(Color.ORANGE);
			_g.fillRect(0, 0, (int)scr.getWidth(), (int)scr.getHeight());
			_g.setColor(old);
			drawBg = false;
		}
		
		// Copio las listas para evitar ConcurrentModificationException
		List<ScreenElement> screenElementListCpy = new ArrayList<ScreenElement>();
		for(int i=0; i<this.queues.size(); i++)
			screenElementListCpy.add(this.queues.get(i).copy());
		drawScreenElementCollection(screenElementListCpy, _g);
		
		screenElementListCpy.clear();
		
		screenElementListCpy = new ArrayList<ScreenElement>();
		for(int i=0; i<this.channels.size(); i++)
			screenElementListCpy.add(this.channels.get(i).copy());
		drawScreenElementCollection(screenElementListCpy, _g);
		
		g.drawImage(this.getDobleBuffer(), 0, 0, (int)scr.getWidth(), (int)scr.getHeight(), this);
	}
	
	private void drawScreenElementCollection(List<ScreenElement> coll, Graphics g) {
		Iterator<ScreenElement> it = coll.iterator();
		while(it.hasNext()) {
			it.next().draw(g);
		}
	}
	
	public List<ScreenElement> getChannels() {
		return this.channels;
	}
	
	public void setChannels(List<ScreenElement> channels) {
		this.channels = channels;
	}
	
	public List<ScreenElement> getQueues() {
		return this.queues;
	}
	
	public void setQueues(List<ScreenElement> queues) {
		this.queues = queues;
	}
	
	public void eraseChannels() {
		this.channels.clear();
	}
	
	public void eraseQueues() {
		this.queues.clear();
	}
	
	private List<ScreenElement> channels;
	private List<ScreenElement> queues;
	private Image doubleBuffer;
	private boolean drawBg = true;
}
